# -*- coding:utf-8 -*-
from socket import *
import simplejson as json
from mycoolpai.initclass import CPConf
from django.core.context_processors import request
from django.shortcuts import render_to_response
from django.http import HttpResponse

def index(request):
    user_email = request.session.get('user_email',None)
    if user_email is None:
        return render_to_response('index.htm')
    else:
        return render_to_response('index.htm',{'title_tips':'success'})

def register(request):

    email_value = request.POST.get('email',None)
    passwd_value = request.POST.get('before_password',None)
    nickname_value = request.POST.get('nickname',None)
    if (email_value is None) or (passwd_value is None) or (nickname_value is None):
        return render_to_response('register.htm')
    else:
        #构造命令包
        msg = dict()
        msg['type'] = 'user_register'
        msg['email'] = email_value
        msg['password'] = passwd_value
        msg['nickname'] = nickname_value
        result = sendMsg(msg)
        if result['type'] == 1:
            #说明注册成功了
            request.session['user_email'] = email_value
            request.session['user_nickname'] = nickname_value
            request.session['user_money'] = result['info']['user_money']
            request.session['user_bonus'] = result['info']['user_bonus']
            return render_to_response('index.htm',{'title_tips':'success'})
        else:
            return render_to_response('register.htm',{'title_tips':result['info']})

def login(request):
    return render_to_response('login.htm')

def check_user_availability(request):
    name_value = request.POST.get('name',None)
    field_type = request.POST.get('field_type',None)
    result_data = None
    
    if (name_value is None) or (field_type is None):
        #什么值都没有，不过应该不会出现这种情况，在前面js中已经检查过了
        print '$terrible error in view.check_user_availability$'
    else:
        #构造命令包
        msg = dict()
        msg['type'] = 'check_user_availability'
        msg['field'] = field_type
        msg['value'] = name_value
        result = sendMsg(msg)
        result_data = result['type']
    return HttpResponse(result_data)


def sendMsg(msg):
    '''发送请求命令给后台，并接收结果'''
    tcpclient = socket(AF_INET,SOCK_STREAM)
    myconf = CPConf()
    tcpport = myconf.getValue("tcp_port")
    mds_ip = myconf.getValue('mds_ip')
    tcpclient.connect((mds_ip,int(tcpport)))
    #tcpclient.send()的内容是unicode编码格式的，要转成gbk或是gb2312格式
    msg = json.dumps(msg)
    tcpclient.send(msg+'\r\n')
    #默认开2KB的缓冲
    result = tcpclient.recv(2048)
    tcpclient.close()
    result = json.loads(result.strip())
    return result
